package com.gitee.kamismile.stoneComEx.common.filter.servlet;


import com.gitee.kamismile.stoneComEx.util.ThreadLocalRequestUtil;
import com.gitee.kamismile.stoneComEx.util.ThreadLocalResponseUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.ContentCachingRequestWrapper;


import java.io.IOException;

//    public class ThreadLocalRequestAndResponseFilter implements Filter {
public class ThreadLocalRequestAndResponseFilter extends OncePerRequestFilter {


    @Override
    public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException,
            ServletException {

//        if (request instanceof ContentCachingRequestWrapper) {
//            chain.doFilter(request, response);
//        } else {
////            ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper((HttpServletResponse) response);
//            ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper(request);
//            ThreadLocalRequestUtil.setRequest(requestWrapper);
//            ThreadLocalResponseUtil.setResponse(response);
//            chain.doFilter(requestWrapper, response);
//        }

        boolean isFirstRequest = !isAsyncDispatch(request);
        HttpServletRequest requestToUse = request;

        if (isFirstRequest && !(request instanceof ContentCachingRequestWrapper)) {
            requestToUse = new ContentCachingRequestWrapper(request);
        }

//        ThreadLocalRequestUtil.setRequest(requestToUse);
//        ThreadLocalResponseUtil.setResponse(response);
        chain.doFilter(requestToUse, response);

    }


}
